import {defineStore} from 'pinia'
import {resetRouter} from '@/router'
import {usePermissionStore, useTagsStore} from '@/store'
import {removeToken, toLogin} from '@/utils'
import api from '@/api'

export const useUserStore = defineStore('user', {
    state() {
        return {
            userInfo: {},
        }
    },
    getters: {
        userId() {
            return this.userInfo?.userId
        },
        name() {
            return this.userInfo?.nickName
        },
        avatar() {
            return this.userInfo?.avatar
        },
        role() {
            return this.userInfo?.roles || []
        },
    },
    actions: {
        async getUserInfo() {
            try {
                const res = await api.getUser()
                this.userInfo = {...res.result}
                return Promise.resolve(res)
            } catch (error) {
                return Promise.reject(error)
            }
        },
        async logout() {
            const {resetTags} = useTagsStore()
            const {resetPermission} = usePermissionStore()
            removeToken()
            resetTags()
            resetPermission()
            resetRouter()
            this.$reset()
            toLogin()
        },
        setUserInfo(userInfo = {}) {
            this.userInfo = {...this.userInfo, ...userInfo}
        },
    },
})
